﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using TomNet.AspNetCore.Mvc;
using TomNet.SqlSugarCore.Entity;
using Microsoft.Extensions.DependencyInjection;
using TomNet.AspNetCore.Data;
using TomNet.Data;
using TomNet.App.Model.DB;
using TomNet.App.Core.Contracts;
using TomNet.Security.Claims;
using TomNet.Caching;
using TomNet.Extensions;
using System.ComponentModel.DataAnnotations;

namespace TomNet.App.Web.Controllers.API
{
	[Common.ApiAuthentication]
	public partial class MyController : Common.APIController
	{
		private readonly IUnitOfWork _unitOfWork;
		private IDistributedCache _cache;
		//private IHttpClientFactory _httpClientFactory;
		private readonly IBusinessContract _businessContract;
		private readonly Core.Contracts.Identity.IUsersContract _usersContract;

		public MyController(
			IUnitOfWork unitOfWork,
			IServiceProvider provider,
			IBusinessContract businessContract,
			Core.Contracts.Identity.IUsersContract usersContract)
		{
			_unitOfWork = unitOfWork;
			_cache = provider.GetService<IDistributedCache>();
			//_httpClientFactory = httpClientFactory;
			_businessContract = businessContract;
			_usersContract = usersContract;
		}

		#region AjaxResult UpdatePasswordCode(UpdatePasswordCodeParameter parameter) 修改密码验证码。

		/// <summary>
		/// 修改密码验证码。
		/// </summary>
		/// <param name="parameter"></param>
		/// <returns></returns>
		[HttpPost]
		public AjaxResult UpdatePasswordCode()
		{
			if (!_unitOfWork.DbContext.Queryable<Model.DB.Identity.UserLogin>().Any(m => m.LoginName == LoginPhone))
			{
				return new AjaxResult("用户不存在", AjaxResultType.Error);
			}

			var check = _cache.Get<string>("PhoneMsgTime_" + LoginPhone);
			if (check != null)
			{
				return new AjaxResult("请勿频繁获取手机验证码", AjaxResultType.Error);
			}

			Random random = new Random();
			var code = random.NextNumberString(5);

			//发送短信

			_cache.Set("PhoneMsgTime_" + LoginPhone, code, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15) });
			_cache.Set("UpdatePassWord_" + LoginPhone, code, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15) });
			return new AjaxResult("验证码已发送，测试 验证码：" + code, AjaxResultType.Success, "");
		}

		#endregion

		#region AjaxResult UpdatePassword(UpdatePasswordParameter parameter) 修改密码。

		/// <summary>
		/// 修改密码。
		/// </summary>
		/// <param name="parameter"></param>
		/// <returns></returns>
		public AjaxResult UpdatePassword(UpdatePasswordParameter parameter)
		{
			var code = _cache.Get<string>("UpdatePassWord_" + LoginPhone);
			if (code != parameter.Code)
			{
				return new AjaxResult("验证码错误", AjaxResultType.Error);
			}

			var userLogin = _unitOfWork.DbContext.Queryable<Model.DB.Identity.UserLogin>().Where(m => m.LoginName == LoginName).First();
			if (userLogin == null)
			{
				return new AjaxResult("用户不存在", AjaxResultType.Error);
			}
			userLogin.Password = parameter.LoginPass;//HashHelper.GetMd5(parameter.Password);

			_unitOfWork.DbContext.Updateable(userLogin).ExecuteCommand();

			return new AjaxResult("密码修改成功", AjaxResultType.Success, LoginName);
		}

		public class UpdatePasswordParameter
		{
			[Required()]
			public string LoginPass { get; set; }

			[Required()]
			public string Code { get; set; }
		}

		#endregion

		#region AjaxResult Address(AddressParameter parameter)  提币地址

		public AjaxResult Address(AddressParameter parameter)
		{
			var query = _unitOfWork.DbContext.Queryable<UserWallet>()
				.Where(p => p.UserId == LoginUserId)
				.Select(p => new AddressRowsModel
				{
					Id = p.Id,
					Address = p.Address,
					IsValid = p.IsValid
				});

			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			//返回数据
			var result = new AddressModel
			{
				Rows = list,
				Total = total
			};
			
			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class AddressParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class AddressModel
		{
			public List<AddressRowsModel> Rows { get; set; } = new List<AddressRowsModel>();
			public int Total { get; set; }
		}

		public class AddressRowsModel
		{
			public int Id { get; set; }
			public string Address { get; set; }
			public bool IsValid { get; set; }
		}

		#endregion

		#region AjaxResult InsertAddress(InsertAddressParameter parameter) 添加提币地址

		public AjaxResult InsertAddress(InsertAddressParameter parameter)
		{
			if (string.IsNullOrWhiteSpace(parameter.Address))
				return new AjaxResult("提币地址不可为空。", AjaxResultType.Error, "");

			int addressCount = _unitOfWork.DbContext.Queryable<UserWallet>().Count(p => p.UserId == LoginUserId);
			if (addressCount > 0)
				return new AjaxResult("已存在相同的提币地址。", AjaxResultType.Error, "");

			UserWallet entity = new UserWallet
			{
				UserId = LoginUserId,
				Address = parameter.Address,
				IsValid = parameter.IsValid
			};
			var count = _unitOfWork.DbContext.Insertable(entity).ExecuteCommand();

			if (count > 0)
				return new AjaxResult("Success", AjaxResultType.Success, "");
			else
				return new AjaxResult("数据保存失败。", AjaxResultType.Error, "");
		}

		public class InsertAddressParameter
		{
			public string Address { get; set; }
			public bool IsValid { get; set; } = false;
		}

		#endregion

		#region AjaxResult SetAddressValid(SetAddressValidParameter parameter) 设置提币地址状态

		public AjaxResult SetAddressValid(SetAddressValidParameter parameter)
		{
			bool has = _unitOfWork.DbContext.Queryable<UserWallet>().Any(p => p.UserId == LoginUserId && p.Id == parameter.Id);
			if (!has)
				return new AjaxResult("不存在指定提币地址。", AjaxResultType.Error, "");

			SqlSugar.SugarParameter[] pars = new SqlSugar.SugarParameter[]
			{
				new SqlSugar.SugarParameter("@Id", parameter.Id)
			};

			_unitOfWork.DbContext.Ado.ExecuteCommand("update UserWallet set [IsValid] = 1 where [Id] = @Id; update UserWallet set [IsValid] = 0 where [Id] <> @Id", pars);

			return new AjaxResult("Success", AjaxResultType.Success, "");
		}

		public class SetAddressValidParameter
		{
			public int Id { get; set; }
		}

		#endregion

		#region AjaxResult DailishangGuanli(DailishangGuanliParameter parameter)  代理商管理

		public AjaxResult DailishangGuanli(DailishangGuanliParameter parameter)
		{
			var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap, Proportions>
				((a, b, c) => a.Id == b.UserId && a.ProportionID == c.Id);
			switch (LoginRoleId)
			{
				case 3:
					query.Where((a, b, c) => a.RoleID == 5 && b.InterfaceId == LoginUserId);
					break;
				case 4:
					query.Where((a, b, c) => a.RoleID == 5 && b.InterfaceSalesmanId == LoginUserId);
					break;
				default:
					query.Where((a, b, c) => a.Id == 0);
					break;
			}

			int total = 0;
			var list = query.Select((a, b, c) => new DailishangGuanliRowsModel
			{
				UserId = a.Id,
				UserName = a.UserName,
				ProportionName = c.Name,
				ProportionRatio = c.Ratio
			}).ToPageList(parameter.Page, parameter.Limit, ref total);

			//数据处理
			foreach (var info in list)
			{
				int kehuCount = _usersContract.UnitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) => a.RoleID == 7 && (b.AgentId == LoginUserId || b.AgentSalesmanId == LoginUserId)).Select((a, b) => a.Id).Count();

				List<int> businessIds = new Service.DAL(_unitOfWork).GetAfterUserIds(info.UserId);

				decimal hashrate = _unitOfWork.DbContext.Queryable<Business>().Where(p => businessIds.Contains(p.Id)).Sum(p => (decimal?)p.Hashrate).GetValueOrDefault();

				decimal totalAmount = _unitOfWork.DbContext.Queryable<BusinessIncomeRunnings>().Where(p => businessIds.Contains(p.Id)).Sum(p => (decimal?)p.Amount).GetValueOrDefault();

				info.KehuCount = kehuCount;
				info.HeyueCount = businessIds.Count;
				info.HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " ");
				info.TotalAmount = totalAmount;
			}

			//返回数据
			var result = new DailishangGuanliModel
			{
				Rows = list,
				Total = total
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class DailishangGuanliParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class DailishangGuanliModel
		{
			public List<DailishangGuanliRowsModel> Rows { get; set; } = new List<DailishangGuanliRowsModel>();
			public int Total { get; set; }
		}

		public class DailishangGuanliRowsModel
		{
			public int UserId { get; set; }
			public string UserName { get; set; }
			public string ProportionName { get; set; }
			public float ProportionRatio { get; set; }
			public int KehuCount { get; set; }
			public int HeyueCount { get; set; }
			public string HashrateString { get; set; }
			public decimal TotalAmount { get; set; }
		}

		#endregion

		#region AjaxResult Dailishang(DailishangParameter parameter)  代理商

		public AjaxResult Dailishang(DailishangParameter parameter)
		{
			var query = _unitOfWork.DbContext.Queryable<Business>()
				.Where(p => p.Id == parameter.Id)
				.Select(p => new DailishangRowsModel
				{
					Hashrate = p.Hashrate,
					HashrateString = "",
					Number = p.Number,
					KuangjiName = "",
					Price = p.Price,
					TotalAmount = p.Price * p.Number,
					CratedTime = p.CreatedTime
				});

			int total = 0;
			var list = query.ToPageList(parameter.Page, parameter.Limit, ref total);

			//数据处理
			foreach(var info in list)
			{
				info.HashrateString = Common.Utility.ConvertHashrate(info.Hashrate, space: " ");
			}

			//用户信息
			string phone = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users>().Where(p => p.Id == LoginUserId).Select(p => p.Phone).First();

			//汇总数据
			var queryIncome = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
				.Where((a, b) => a.UserId == parameter.Id);

			decimal totalAmount = queryIncome.Sum((a,b) => (decimal?)a.Amount).GetValueOrDefault();
			decimal totalElectricCharge = queryIncome.Sum((a,b) => (decimal?)b.ElectricChargeBTC).GetValueOrDefault();
			decimal totalShouyi = totalAmount + totalElectricCharge;

			//返回数据
			var result = new DailishangModel
			{
				Rows = list,
				Total = total,
				Phone = phone,
				TotalAmount = totalAmount,
				TotalShouyi = totalShouyi,
				TotalElectricCharge = totalElectricCharge
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class DailishangParameter
		{
			public int Id { get; set; }
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class DailishangModel
		{
			public List<DailishangRowsModel> Rows { get; set; } = new List<DailishangRowsModel>();
			public int Total { get; set; }
			public string Phone { get; set; }
			public decimal TotalAmount { get; set; }//净收益（不含电费的收益）
			public decimal TotalShouyi { get; set; }//总收益
			public decimal TotalElectricCharge { get; set; }//电费（BTC）
		}

		public class DailishangRowsModel
		{
			public decimal Hashrate { get; set; }
			public string HashrateString { get; set; }
			public int Number { get; set; }
			public string KuangjiName { get; set; }
			public decimal Price { get; set; }
			public decimal TotalAmount { get; set; }
			public DateTime CratedTime { get; set; }
		}

		#endregion

		#region AjaxResult YewuyuanGuanli(YewuyuanGuanliParameter parameter)  业务员管理

		public AjaxResult YewuyuanGuanli(YewuyuanGuanliParameter parameter)
		{
			var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>
				((a, b) => a.Id == b.UserId);
			switch (LoginRoleId)
			{
				case 3:
					query.Where((a, b) => a.RoleID == 4 && b.InterfaceId == LoginUserId);
					break;
				case 5:
					query.Where((a, b) => a.RoleID == 6 && b.AgentId == LoginUserId);
					break;
				default:
					return new AjaxResult("无访问权限", AjaxResultType.Error, "");
			}

			int total = 0;
			var list = query.Select((a, b) => new YewuyuanGuanliRowsModel
			{
				UserId = a.Id,
				UserName = a.UserName,
			}).ToPageList(parameter.Page, parameter.Limit, ref total);

			//数据处理
			foreach (var info in list)
			{
				int kehuCount = _usersContract.UnitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) => a.RoleID == 7 && (b.InterfaceSalesmanId == LoginUserId || b.AgentSalesmanId == LoginUserId)).Select((a, b) => a.Id).Count();

				List<int> businessIds = new Service.DAL(_unitOfWork).GetAfterBusinessIds(info.UserId);

				decimal hashrate = _unitOfWork.DbContext.Queryable<Business>().Where(p => businessIds.Contains(p.Id)).Sum(p => (decimal?)p.Hashrate).GetValueOrDefault();

				decimal totalAmount = _unitOfWork.DbContext.Queryable<BusinessIncomeRunnings>().Where(p => businessIds.Contains(p.Id)).Sum(p => (decimal?)p.Amount).GetValueOrDefault();

				info.KehuCount = kehuCount;
				info.HeyueCount = businessIds.Count;
				info.HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " ");
				info.TotalAmount = totalAmount;
			}

			//返回数据
			var result = new YewuyuanGuanliModel
			{
				Rows = list,
				Total = total
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class YewuyuanGuanliParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class YewuyuanGuanliModel
		{
			public List<YewuyuanGuanliRowsModel> Rows { get; set; } = new List<YewuyuanGuanliRowsModel>();
			public int Total { get; set; }
		}

		public class YewuyuanGuanliRowsModel
		{
			public int UserId { get; set; }
			public string UserName { get; set; }
			public int KehuCount { get; set; }
			public int HeyueCount { get; set; }
			public string HashrateString { get; set; }
			public decimal TotalAmount { get; set; }
		}

		#endregion

		#region AjaxResult InsertYewuyuan(InsertYewuyuanParameter parameter)  添加业务员

		public AjaxResult InsertYewuyuan(InsertYewuyuanParameter parameter)
		{
			if (!new int[] { 3, 5 }.Contains(LoginRoleId))
				return new AjaxResult("无访问权限", AjaxResultType.Error, "");

			if (_unitOfWork.DbContext.Queryable<Model.DB.Identity.Users>().Any(p => p.UserName == parameter.UserName))
			{
				return new AjaxResult("用户名已存在", AjaxResultType.Error, "");
			}

			if (_unitOfWork.DbContext.Queryable<Model.DB.Identity.UserLogin>().Any(p => p.LoginName == parameter.Phone))
			{
				return new AjaxResult("手机号已存在", AjaxResultType.Error, "");
			}

			Model.DB.Identity.Users entityUser = new Model.DB.Identity.Users
			{
				Code = "",
				CreatedTime = DateTime.Now,
				Email = "",
				IdNumber = "",
				IsDeleted = false,
				Phone = parameter.Phone,
				ProportionID = 0,
				RoleID = LoginRoleId + 1,
				Sex = true,
				UserName = parameter.UserName,
				Token = ""
			};
			entityUser = _unitOfWork.DbContext.Insertable(entityUser).ExecuteReturnEntity();

			Model.DB.Identity.UserLogin entityLogin = new Model.DB.Identity.UserLogin
			{
				IsDeleted = false,
				LoginName = parameter.Phone,
				LoginType = 1,
				Password = parameter.Phone,
				UserID = entityUser.Id
			};
			_unitOfWork.DbContext.Insertable(entityLogin).ExecuteCommand();

			Model.DB.Identity.UserRoleMap entityRoleMap = new Model.DB.Identity.UserRoleMap
			{
				UserId = entityUser.Id,
				RoleId = LoginRoleId + 1
			};
			_unitOfWork.DbContext.Insertable(entityRoleMap).ExecuteCommand();

			return new AjaxResult("业务员添加成功", AjaxResultType.Success, "");
		}

		public class InsertYewuyuanParameter
		{
			public string UserName { get; set; }
			public string Phone { get; set; }
		}

		#endregion

		#region AjaxResult WodeKehu(WodeKehuParameter parameter)  我的客户

		public AjaxResult WodeKehu(WodeKehuParameter parameter)
		{
			//登录用户的所有下级用户Id集合
			List<int> userIds = new Service.DAL(_unitOfWork).GetAfterUserIds(LoginUserId);

			//数据查询
			var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId);

			switch (parameter.UserId)
			{
				case -2:
					userIds = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users>().Where(p => userIds.Contains(p.Id) && p.RoleID == LoginRoleId + 1).Select(p => p.Id).ToList();//业务员
					query.Where((a, b) => userIds.Contains(b.InterfaceSalesmanId) && a.RoleID == 7);
					break;
				case -1:
					userIds = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users>().Where(p => userIds.Contains(p.Id) && p.RoleID == 5).Select(p => p.Id).ToList();//下级代理商
					query.Where((a, b) => userIds.Contains(b.AgentId) && a.RoleID == 7);
					break;
				case 0:
					query.Where((a, b) => b.InterfaceId == LoginUserId && a.RoleID == 7);
					break;
				default:
					query.Where((a, b) => (b.InterfaceSalesmanId == parameter.UserId || b.AgentId == parameter.UserId || b.AgentSalesmanId == parameter.UserId) && a.RoleID == 7);
					break;
			}

			int total = 0;
			var list = query.Select((a,b) => new WodeKehuRowsModel
			{
				UserId = a.Id,
				UserName = a.UserName,
				CreatedTime = a.CreatedTime
			}).ToPageList(parameter.Page, parameter.Limit, ref total);

			//数据处理
			foreach (var info in list)
			{
				string salesmanName = string.Empty;

				salesmanName = _unitOfWork.DbContext.Queryable<Model.DB.Identity.UserMap, Model.DB.Identity.Users>((a, b) => a.AgentSalesmanId == b.Id)
					.Where((a, b) => a.UserId == info.UserId)
					.Select((a, b) => b.UserName).First();
				if(string.IsNullOrWhiteSpace(salesmanName))
				{
					salesmanName = _unitOfWork.DbContext.Queryable<Model.DB.Identity.UserMap, Model.DB.Identity.Users>((a, b) => a.InterfaceSalesmanId == b.Id)
						.Where((a, b) => a.UserId == info.UserId)
						.Select((a, b) => b.UserName).First();
				}

				int heyueCount = _unitOfWork.DbContext.Queryable<Business>().Where(p => p.UserId == info.UserId).Select(p => p.Id).Count();

				decimal hashrate = _unitOfWork.DbContext.Queryable<Business>().Where(p => p.UserId == info.UserId).Sum(p => (decimal?)p.Hashrate).GetValueOrDefault();

				decimal totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
					.Where((a, b) => a.UserId == info.UserId)
					.Sum((a,b) => (decimal?)b.Amount).GetValueOrDefault();

				info.SalesmanName = salesmanName;
				info.HeyueCount = heyueCount;
				info.HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " ");
				info.TotalAmount = totalAmount;
			}

			//返回数据
			var result = new WodeKehuModel
			{
				Rows = list,
				Total = total
			};

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class WodeKehuParameter
		{
			public int UserId { get; set; } = 0;//用户Id，返回指定用户Id的客户（0为全部客户；-1为代理商客户；-2为业务经理客户；大于0为指定用户）
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}

		public class WodeKehuModel
		{
			public List<WodeKehuRowsModel> Rows { get; set; } = new List<WodeKehuRowsModel>();
			public int Total { get; set; }
		}

		public class WodeKehuRowsModel
		{
			public int UserId { get; set; }
			public string UserName { get; set; }
			public string SalesmanName { get; set; }
			public int HeyueCount { get; set; }
			public string HashrateString { get; set; }
			public decimal TotalAmount { get; set; }
			public DateTime CreatedTime { get; set; }
		}

		#endregion
		#region AjaxResult KehuSaixuan()  客户筛选

		public AjaxResult KehuSaixuan()
		{
			KehuSaixuanModel result = new KehuSaixuanModel();

			List<int> userIds = new List<int>();
			List<int> businessIds = new List<int>();
			int kehuCount = 0;
			int heyueCount = 0;
			decimal hashrate = 0;
			decimal totalAmount = 0;

			#region 全部客户

			if (new int[] { 3, 4, 5, 6 }.Contains(LoginRoleId))
			{
				var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId).Where((a, b) => a.RoleID == 7);
				switch (LoginRoleId)
				{
					case 3:
						query.Where((a, b) => b.InterfaceId == LoginUserId);
						break;
					case 4:
						query.Where((a, b) => b.InterfaceSalesmanId == LoginUserId);
						break;
					case 5:
						query.Where((a, b) => b.AgentId == LoginUserId);
						break;
					case 6:
						query.Where((a, b) => b.AgentSalesmanId == LoginUserId);
						break;
				}
				kehuCount = query.Select((a, b) => a.Id).Count();
				userIds = query.Select((a, b) => a.Id).ToList();

				var queryBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => userIds.Contains(p.UserId));
				heyueCount = queryBusiness.Select(p => p.Id).Count();
				hashrate = queryBusiness.Sum(p => (decimal?)p.Hashrate * p.Number).GetValueOrDefault();
				businessIds = queryBusiness.Select(p => p.Id).ToList();

				totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
					.Where((a, b) => businessIds.Contains(a.Id))
					.Sum((a, b) => (decimal?)b.Amount).GetValueOrDefault();

				result.Quanbu = new KehuSaixuanRowsModel
				{
					UserId = 0,
					UserName = "全部客户",
					KehuCount = kehuCount,
					HeyueCount = heyueCount,
					Hashrate = hashrate,
					HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " "),
					TotalAmount = totalAmount
				};
			}

			#endregion

			#region 代理商客户

			if (new int[] { 3, 4 }.Contains(LoginRoleId))
			{
				//代理商Id集合
				var queryUser = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId).Where((a, b) => a.RoleID == 5);
				switch (LoginRoleId)
				{
					case 3:
						queryUser.Where((a, b) => b.InterfaceId == LoginUserId);
						break;
					case 4:
						queryUser.Where((a, b) => b.InterfaceSalesmanId == LoginUserId);
						break;
				}
				userIds = queryUser.Select((a, b) => a.Id).ToList();

				//客户信息
				var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) => userIds.Contains(b.AgentId) && a.RoleID == 7);
				kehuCount = query.Select((a, b) => a.Id).Count();
				userIds = query.Select((a, b) => a.Id).ToList();

				var queryBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => userIds.Contains(p.UserId));
				heyueCount = queryBusiness.Select(p => p.Id).Count();
				hashrate = queryBusiness.Sum(p => (decimal?)p.Hashrate * p.Number).GetValueOrDefault();
				businessIds = queryBusiness.Select(p => p.Id).ToList();

				totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
					.Where((a, b) => businessIds.Contains(a.Id))
					.Sum((a, b) => (decimal?)b.Amount).GetValueOrDefault();

				result.Dailishang = new KehuSaixuanRowsModel
				{
					UserId = -1,
					UserName = "代理商客户",
					KehuCount = kehuCount,
					HeyueCount = heyueCount,
					Hashrate = hashrate,
					HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " "),
					TotalAmount = totalAmount
				};
			}

			#endregion

			#region 业务经理客户

			if (new int[] { 3, 5 }.Contains(LoginRoleId))
			{

				//业务经理Id集合
				var queryUser = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId).Where((a, b) => a.RoleID == LoginRoleId + 1);
				switch (LoginRoleId)
				{
					case 3:
						queryUser.Where((a, b) => b.InterfaceId == LoginUserId);
						break;
					case 5:
						queryUser.Where((a, b) => b.AgentId == LoginUserId);
						break;
				}
				userIds = queryUser.Select((a, b) => a.Id).ToList();

				//客户信息
				var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) => (userIds.Contains(b.InterfaceSalesmanId) || userIds.Contains(b.AgentSalesmanId)) && a.RoleID == 7);
				kehuCount = query.Select((a, b) => a.Id).Count();
				userIds = query.Select((a, b) => a.Id).ToList();

				var queryBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => userIds.Contains(p.UserId));
				heyueCount = queryBusiness.Select(p => p.Id).Count();
				hashrate = queryBusiness.Sum(p => (decimal?)p.Hashrate * p.Number).GetValueOrDefault();
				businessIds = queryBusiness.Select(p => p.Id).ToList();

				totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
					.Where((a, b) => businessIds.Contains(a.Id))
					.Sum((a, b) => (decimal?)b.Amount).GetValueOrDefault();

				result.Dailishang = new KehuSaixuanRowsModel
				{
					UserId = -2,
					UserName = "业务经理客户",
					KehuCount = kehuCount,
					HeyueCount = heyueCount,
					Hashrate = hashrate,
					HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " "),
					TotalAmount = totalAmount
				};
			}

			#endregion

			#region 代理商列表

			if (new int[] { 3, 4 }.Contains(LoginRoleId))
			{
				var list = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) => (b.InterfaceId == LoginUserId || b.InterfaceSalesmanId == LoginUserId) && a.RoleID == 5)
					.Select((a, b) => a).ToList();

				foreach(var info in list)
				{
					//客户信息
					var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
						.Where((a, b) => userIds.Contains(b.AgentId) && a.RoleID == 7);
					kehuCount = query.Select((a, b) => a.Id).Count();
					userIds = query.Select((a, b) => a.Id).ToList();

					var queryBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => userIds.Contains(p.UserId));
					heyueCount = queryBusiness.Select(p => p.Id).Count();
					hashrate = queryBusiness.Sum(p => (decimal?)p.Hashrate * p.Number).GetValueOrDefault();
					businessIds = queryBusiness.Select(p => p.Id).ToList();

					totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
						.Where((a,b)=>businessIds.Contains(a.Id))
						.Sum((a, b) => (decimal?)b.Amount).GetValueOrDefault();

					result.DailishangRows.Add(new KehuSaixuanRowsModel
					{
						UserId = info.Id,
						UserName = info.UserName,
						KehuCount = kehuCount,
						HeyueCount = heyueCount,
						Hashrate = hashrate,
						HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " "),
						TotalAmount = totalAmount
					});
				}
			}

			#endregion

			#region 业务经理列表

			if (new int[] { 3, 5 }.Contains(LoginRoleId))
			{
				var list = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
					.Where((a, b) =>(b.InterfaceId == LoginUserId || b.AgentId == LoginUserId) && a.RoleID == LoginRoleId + 1)
					.Select((a, b) => a).ToList();

				foreach (var info in list)
				{
					//客户信息
					var query = _unitOfWork.DbContext.Queryable<Model.DB.Identity.Users, Model.DB.Identity.UserMap>((a, b) => a.Id == b.UserId)
						.Where((a, b) => (userIds.Contains(b.InterfaceSalesmanId) || userIds.Contains(b.AgentSalesmanId)) && a.RoleID == 7);
					kehuCount = query.Select((a, b) => a.Id).Count();
					userIds = query.Select((a, b) => a.Id).ToList();

					var queryBusiness = _unitOfWork.DbContext.Queryable<Business>().Where(p => userIds.Contains(p.UserId));
					heyueCount = queryBusiness.Select(p => p.Id).Count();
					hashrate = queryBusiness.Sum(p => (decimal?)p.Hashrate * p.Number).GetValueOrDefault();
					businessIds = queryBusiness.Select(p => p.Id).ToList();

					totalAmount = _unitOfWork.DbContext.Queryable<Business, BusinessIncomeRunnings>((a, b) => a.Id == b.BusinessId)
						.Where((a, b) => businessIds.Contains(a.Id))
						.Sum((a, b) => (decimal?)b.Amount).GetValueOrDefault();

					result.YewuJingliRows.Add(new KehuSaixuanRowsModel
					{
						UserId = info.Id,
						UserName = info.UserName,
						KehuCount = kehuCount,
						HeyueCount = heyueCount,
						Hashrate = hashrate,
						HashrateString = Common.Utility.ConvertHashrate(hashrate, space: " "),
						TotalAmount = totalAmount
					});
				}
			}

			#endregion

			return new AjaxResult("Success", AjaxResultType.Success, result);
		}

		public class KehuSaixuanModel
		{
			public KehuSaixuanRowsModel Quanbu { get; set; } = new KehuSaixuanRowsModel();
			public KehuSaixuanRowsModel Dailishang { get; set; } = new KehuSaixuanRowsModel();
			public KehuSaixuanRowsModel YewuJingli { get; set; } = new KehuSaixuanRowsModel();
			public List<KehuSaixuanRowsModel> DailishangRows { get; set; } = new List<KehuSaixuanRowsModel>();
			public List<KehuSaixuanRowsModel> YewuJingliRows { get; set; } = new List<KehuSaixuanRowsModel>();
		}

		public class KehuSaixuanRowsModel
		{
			public int UserId { get; set; }//规则参照我的客户
			public string UserName { get; set; } = string.Empty;
			public int KehuCount { get; set; }
			public int HeyueCount { get; set; }
			public decimal Hashrate { get; set; }
			public string HashrateString { get; set; } = string.Empty;
			public decimal TotalAmount { get; set; }
		}

		#endregion
		#region AjaxResult InsertProportions(InsertProportionsParameter parameter)  添加分成模式

		public AjaxResult InsertProportions(InsertProportionsParameter parameter)
		{			
			if (_unitOfWork.DbContext.Queryable<Proportions>().Any(p => p.Name == parameter.Name))
			{
				return new AjaxResult("名称已存在", AjaxResultType.Error, "");
			}

			Proportions entity = new Proportions
			{
				UserID = LoginUserId,
				Name = parameter.Name,
				Remark = "",
				Ratio = parameter.Ratio,

			};
			var count = _unitOfWork.DbContext.Insertable(entity).ExecuteCommand();

			if (count > 0)
				return new AjaxResult("Success", AjaxResultType.Success, "");
			else
				return new AjaxResult("数据添加失败。", AjaxResultType.Error, "");
		}

		public class InsertProportionsParameter
		{
			public string Name { get; set; }
			public float Ratio { get; set; }
		}

		#endregion
		#region AjaxResult ProportionsList(ProportionsListParameter parameter)  邀请代理商

		public AjaxResult ProportionsList(ProportionsListParameter parameter)
		{
			if (LoginRoleId!=3)
				return new AjaxResult("无访问权限", AjaxResultType.Error, "");

			int total = 0;
			var data = _unitOfWork.DbContext.Queryable<Proportions>().Where(m => m.UserID == LoginUserId).Select(m => new ProportionsListPModel
			{
				ID = m.Id,
				Name = m.Name,							
				Ratio = m.Ratio,			

			});
			//分页及数据处理            
			var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
			//返回数据
			var result = new ProportionsListModel
			{
				Rows = list,
				Total = total
			};
			return new AjaxResult("允许访问", AjaxResultType.Success, result);
		}

		public class ProportionsListParameter
		{
			public int Page { get; set; } = 1;
			public int Limit { get; set; } = 20;
		}	

		public class ProportionsListModel
		{
			public List<ProportionsListPModel> Rows { get; set; } = new List<ProportionsListPModel>();
			public int Total { get; set; }
		}

		public class ProportionsListPModel
		{
			public int ID { get; set; }			
			public string Name { get; set; }			
			/// <summary>
			/// 奖励比率
			/// </summary>
			public float Ratio { get; set; }			
		}

		#endregion
	}
}
